package indi.dbfmp.oio.oauth.core.event.delete;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import indi.dbfmp.oio.oauth.core.entity.Event;
import indi.dbfmp.oio.oauth.core.entity.GroupRole;
import indi.dbfmp.oio.oauth.core.enums.EventStatus;
import indi.dbfmp.oio.oauth.core.event.RecoveryEvent;
import indi.dbfmp.oio.oauth.core.event.update.GroupsUpdateEvent;
import indi.dbfmp.oio.oauth.core.innerService.IEventInnerService;
import indi.dbfmp.oio.oauth.core.innerService.IUsersBackInnerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

/**
 * <p>
 *
 * </p>
 *
 * @author dbfmp
 * @name: DeleteUserEventListener
 * @since 2021/3/14 下午8:52
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class DeleteUserEventListener implements RecoveryEvent<DeleteUserEvent> {

    private final RedissonClient redissonClient;

    private final IEventInnerService eventInnerService;

    private final IUsersBackInnerService usersBackInnerService;


    /**
     * 恢复通知操作
     * <p>
     * 把json格式的event事件转换为实际参数，进行调用
     *
     * @param eventId         事件id
     * @param eventJsonParams eventJsonParams
     */
    @Override
    public void recoveryEventAction(String eventId, String eventJsonParams) {
        RLock lock = redissonClient.getLock(eventId);
        boolean lockFlag = false;
        try {
            lockFlag = lock.tryLock();
            if (lockFlag) {
                DeleteUserEvent event = JSONObject.parseObject(eventJsonParams, DeleteUserEvent.class);
                this.eventAction(event);
            } else {
                log.warn("获取不到事件ID锁:{},退出！",eventId);
            }
        } catch (Exception e) {
            log.error("锁内执行事件失败！", e);
            log.error("锁内执行事件失败！event:{}", eventId);
        } finally {
            if (lockFlag) {
                lock.unlock();
            }
        }
    }

    @Override
    public void eventAction(DeleteUserEvent delEvent) {
        log.info("收到删除用户事件,DeleteUserEvent:{}", delEvent);
        Event event = new Event();
        event.setId(delEvent.getEventId());
        event.setEventStatus(EventStatus.PROCESSING.name());
        eventInnerService.updateById(event);
        usersBackInnerService.save(delEvent.getUsersBack());
        event.setEventStatus(EventStatus.SUCCESS.name());
        event.setRemarks("更新成功！");
        eventInnerService.updateById(event);
        log.info("DeleteUserEvent,更新结束");
    }
}
